import { InboxOutlined } from '@ant-design/icons';
import { ModalForm, ProFormUploadButton } from '@ant-design/pro-components';
import { message, Typography, Upload } from 'antd';
import React, { useRef } from 'react';

const { Dragger } = Upload;
const { Text } = Typography;

interface FileUploadModalProps {
  trigger: React.ReactNode;
  onSuccess: () => void;
}

interface UploadResponse {
  code: number;
  message?: string;
  data?: any;
}

const FileUploadModal: React.FC<FileUploadModalProps> = ({ trigger, onSuccess }) => {
  const formRef = useRef<any>();

  return (
    <ModalForm
      title="上传文件"
      trigger={trigger as any}
      formRef={formRef}
      modalProps={{
        destroyOnClose: true,
        onCancel: () => {
          formRef.current?.resetFields();
        },
        width: 500,
      }}
      onFinish={async (values) => {
        if (values.file?.[0]?.status === 'done') {
          message.success('上传成功');
          onSuccess();
          return true;
        }
        return false;
      }}
    >
      <ProFormUploadButton
        name="file"
        label="选择文件"
        max={1}
        fieldProps={{
          name: 'file',
          accept: '*',
          beforeUpload: (file) => {
            const isLt100M = file.size / 1024 / 1024 < 100;
            if (!isLt100M) {
              message.error('文件大小不能超过 100MB!');
              return false;
            }
            return true;
          },
          customRequest: ({ file, onSuccess, onError }) => {
            const formData = new FormData();
            formData.append('file', file);
            fetch('/api/file/upload', {
              method: 'POST',
              body: formData,
            })
              .then((res) => res.json())
              .then((res) => {
                const response = res as UploadResponse;
                if (!!response.data) {
                  onSuccess?.(response);
                } else {
                  onError?.(new Error(response.message || '上传失败'));
                }
              })
              .catch((err) => {
                onError?.(err);
              });
          },
          itemRender: (originNode, file) => {
            return (
              <div className="upload-preview">
                <div className="upload-preview-content">
                  <InboxOutlined style={{ fontSize: 48, color: '#1890ff', marginBottom: 16 }} />
                  <div className="upload-preview-text">{file.name}</div>
                </div>
              </div>
            );
          },
        }}
        action="/api/file/upload"
        rules={[{ required: true, message: '请选择文件' }]}
        onChange={async (info) => {
          const { status, response } = info.file;
          if (status === 'done') {
            if (!!response?.data) {
              message.success('上传成功');
              onSuccess();
              formRef.current?.resetFields();
              return true;
            } else {
              message.error(response?.message || '上传失败');
            }
          } else if (status === 'error') {
            message.error('上传失败');
          }
        }}
        extra={
          <div style={{ marginTop: 8 }}>
            <Text type="secondary">支持任意类型文件，单个文件不超过100MB</Text>
          </div>
        }
        buttonProps={{
          className: 'upload-button',
          style: {
            width: '100%',
            height: '200px',
            border: '2px dashed #d9d9d9',
            borderRadius: '8px',
            backgroundColor: '#fafafa',
            display: 'flex',
            flexDirection: 'column' as const,
            justifyContent: 'center',
            alignItems: 'center',
            cursor: 'pointer',
            transition: 'all 0.3s',
          },
        }}
        icon={<InboxOutlined style={{ fontSize: 48, color: '#1890ff', marginBottom: 16 }} />}
        title="点击或拖拽文件到此处上传"
      />
      <style>
        {`
          .upload-button:hover {
            border-color: #1890ff !important;
            background-color: #f0f7ff !important;
          }
          .upload-preview {
            width: 100%;
            height: 200px;
            border: 2px dashed #d9d9d9;
            border-radius: 8px;
            background-color: #fafafa;
            display: flex;
            align-items: center;
            justify-content: center;
            transition: all 0.3s;
          }
          .upload-preview:hover {
            border-color: #1890ff;
            background-color: #f0f7ff;
          }
          .upload-preview-content {
            display: flex;
            flex-direction: column;
            align-items: center;
            justify-content: center;
          }
          .upload-preview-text {
            margin-top: 8px;
            color: #666;
            text-align: center;
            word-break: break-all;
            padding: 0 16px;
          }
        `}
      </style>
    </ModalForm>
  );
};

export default FileUploadModal;
